import { _decorator, Component, Sprite, SpriteFrame } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FrameAnimation')
export class FrameAnimation extends Component {
    @property({ type: [SpriteFrame] })
    frames: SpriteFrame[] = [];

    @property
    interval: number = 0.1;

    @property
    loop: boolean = false;

    @property
    playOnLoad: boolean = false;

    @property
    isAutoDestroy: boolean = false;

    private _sprite: Sprite | null = null;
    private _isPlaying: boolean = false;
    private _currentIndex: number = 0;
    private _accumTime: number = 0;
    private _callback: ((data: any) => void) | null = null;
    private _callBackData: any = null;

    onLoad() {
        this._sprite = this.getComponent(Sprite);
    }

    start() {
        this.reset();

        if (this.playOnLoad) {
            this.play();
        }
    }

    update(dt: number) {
        if (!this._isPlaying || !this._sprite) return;

        this._accumTime += dt;
        if (this._accumTime >= this.interval) {
            this._accumTime = 0;
            this._currentIndex++;

            if (this._currentIndex >= this.frames.length) {
                if (this.loop) {
                    this._currentIndex = 0;
                } else {
                    this._isPlaying = false;
                    this._callback?.(this._callBackData);

                    if (this.isAutoDestroy) {
                        this.node.destroy();
                    }

                    return;
                }
            }

            this._sprite.spriteFrame = this.frames[this._currentIndex];
        }
    }

    play(callback?: (data: any) => void, data?: any) {
        this._isPlaying = true;
        this._callback = callback || null;
        this._callBackData = data || null;
    }

    pause() {
        this._isPlaying = false;
    }

    resume() {
        this._isPlaying = true;
    }

    stop() {
        this._isPlaying = false;
        this.reset();
    }

    reset() {
        this._currentIndex = 0;
        this._accumTime = 0;
        if (this._sprite && this.frames.length > 0) {
            this._sprite.spriteFrame = this.frames[0];
        }
    }

    isPlaying(): boolean {
        return this._isPlaying;
    }

    // 下一帧
    nextFrame() {
        if (this._sprite && this.frames.length > 0) {
            this._currentIndex = (this._currentIndex + 1) % this.frames.length;
            this._sprite.spriteFrame = this.frames[this._currentIndex];
        }
    }
}
